package com.cangxuan.manage.service.impl;

import com.cangxuan.manage.bean.Page;
import com.cangxuan.manage.dao.IGoodsDao;
import com.cangxuan.manage.dao.IOrderDao;
import com.cangxuan.manage.dao.IUserFollowDao;
import com.cangxuan.manage.dao.IUserGoodsDao;
import com.cangxuan.manage.entity.Goods;
import com.cangxuan.manage.exception.ServiceException;
import com.cangxuan.manage.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class GoodsServiceImpl implements IGoodsService {

    IGoodsDao goodsDao;
    IUserGoodsDao userGoodsDao;
    IOrderDao orderDao;
    IUserFollowDao userFollowDao;
    @Autowired
    public void setGoodsDao(IGoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }
    @Autowired
    public void setUserGoodsDao(IUserGoodsDao userGoodsDao) {
        this.userGoodsDao = userGoodsDao;
    }
    @Autowired
    public void setOrderDao(IOrderDao orderDao) {
        this.orderDao = orderDao;
    }
    @Autowired
    public void setUserFollowDao(IUserFollowDao userFollowDao) {
        this.userFollowDao = userFollowDao;
    }

    @Override
    public Page<Goods> page(int pageIndex, int pageSize, Integer seriesId, String name, String code) {
        Page<Goods> goodsPage = new Page<>(pageIndex, pageSize);
        goodsPage.setRecords(goodsDao.select(pageIndex, pageSize,seriesId, name + "%", code));
        goodsPage.setTotal(goodsDao.selectCount(seriesId, name + "%", code));
        return goodsPage;
    }

    @Override
    public Goods get(int id) {
        return goodsDao.selectById(id);
    }

    @Override
    public boolean save(Goods goods) {
        return goods.getId() == 0 ? goodsDao.insert(goods) > 0 : goodsDao.update(goods) > 0;
    }

    @Override
    public boolean remove(int id) {
        //查询当前藏品的挂单数量
        if (userGoodsDao.selectCount(id) > 0) {
            throw new ServiceException(402, "该藏品已被用户持有，暂无法删除");
        }
        if (orderDao.selectCount(id) > 0) {
            throw new ServiceException(402, "该藏品已被用户下单，暂无法删除");
        }
        if (userFollowDao.selectCount(id) > 0) {
            throw new ServiceException(402, "该藏品已被用户收藏，暂无法删除");
        }
        if (goodsDao.delete(id) == 0) {
            throw new ServiceException(402, "删除失败，ID不存在");
        }
        return true;
    }

}
